﻿using System;
using System.IO;
using System.Net;
using System.Web;
using System.Text.RegularExpressions;
using TruckWatch.Cloud.Models;

namespace TruckWatch.Cloud.BusinessLogic
{
    /// <summary>
    /// reference: http://www.storm-consultancy.com/blog/development/code-snippets/using-google-maps-api-to-get-latitude-longitude-co-ordinates-from-postcode-or-address/
    /// </summary>
    public class GoogleMaps
    {
        private const string API_KEY = "ABQIAAAAcZ82cZMYCeoT7sdwI9e_JhSDYaaniH8lw7Xd6PPwzaCdrqY-GBRW2wW7l2N75A8bI4fSOT32Cp87KA";

        /// <param name="addr">The address in CSV form line1, line2, postcode</param>
        /// reference: http://code.google.com/apis/maps/signup.html
        /// <returns>LatLng object</returns>
        public static TripPointNEF GetLatLng(string addr)
        {
            var url = "http://maps.google.co.uk/maps/geo?output=csv&key=" + API_KEY + "&q=" + HttpContext.Current.Server.UrlEncode(addr);

            string response = GetStringFromWebRequest(url);
            if (response == null)
                return null;

            var parts = response.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

            return new TripPointNEF(Convert.ToDouble(parts[2]), Convert.ToDouble(parts[3]));
        }

        /// reference: http://code.google.com/apis/maps/signup.html
        /// <returns>first of the addresses returned (should be the most specific)</returns>
        public static string GetAddress(TripPointNEF latLng)
        {
            string url = string.Format("http://maps.googleapis.com/maps/api/geocode/json?latlng={0},{1}&sensor=true", latLng.Latitude, latLng.Longitude);

            string response = GetStringFromWebRequest(url);
            if (response == null)
                return null;

            string address = Regex.Match(response, "formatted_address\":(.*)").Groups[1].Value;
            return address == null ? null : address.Trim(new char[] {' ', '"', ',' });
        }

        private static string GetStringFromWebRequest(string url)
        {
            var request = WebRequest.Create(url);
            var response = (HttpWebResponse)request.GetResponse();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                MemoryStream ms = new MemoryStream();
                var responseStream = response.GetResponseStream();

                var buffer = new Byte[2048];
                int count = responseStream.Read(buffer, 0, buffer.Length);

                while (count > 0)
                {
                    ms.Write(buffer, 0, count);
                    count = responseStream.Read(buffer, 0, buffer.Length);
                }

                responseStream.Close();
                ms.Close();

                var responseBytes = ms.ToArray();
                var encoding = new System.Text.ASCIIEncoding();

                return encoding.GetString(responseBytes);
            }
            return null;
        }
    }
}

